package com.invengo.module_check.ui.fragment.offline_collect;

import android.annotation.SuppressLint;
import android.app.Application;
import android.os.Build;

import com.invengo.library_db.entity.module_check.BookBean;
import com.invengo.library_rfid.classify.AnalyzeImpl;
import com.invengo.library_rfid.classify.RFIDCallBackListener;
import com.invengo.library_rfid.entity.TagInfo;
import com.invengo.module_check.BR;
import com.invengo.module_check.R;
import com.invengo.module_check.data.repsitory.business.BusinessRepsitory;
import com.invengo.module_check.ui.fragment.offline_collect.item.OfflineCollectItmeViewModel;

import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import java8.util.stream.StreamSupport;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.ItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class OfflineCollectViewModel extends BaseViewModel<BusinessRepsitory> {

    public RFIDCallBackListener rfidService = new RFIDCallBackListener(AnalyzeImpl.TO_BOOK, tagInfo -> onScanResult(tagInfo), state -> isReading.set(state));
    public BindingRecyclerViewAdapter adapter = new BindingRecyclerViewAdapter();
    public ObservableList<OfflineCollectItmeViewModel> bookItemList = new ObservableArrayList<>();
    public ItemBinding<OfflineCollectItmeViewModel> bookitemBinding = ItemBinding.of(BR.viewModel, R.layout.item_offline_collect);

    public OfflineCollectViewModel(@NonNull Application application) {
        super(application, BusinessRepsitory.getInstance());
        registerRFID(rfidService);
    }

    //    @Override
    public void onScanResult(TagInfo tagInfo) {
        switch (tagInfo.getRfidModel()) {
//            case TID:
//                if (tagInfo.getScanModel() == AnalyzeImpl.TO_SHELF) {
////                    getShelfByTid(tagInfo.getTag());
//                } else
//                    getBookByTid(tagInfo.getTag());
//                break;
            case EPC:
            case U_DATA:
                BookBean bean = new BookBean();
                bean.setTid(tagInfo.getTid());
                bean.setBarCode(tagInfo.getTag());
                bean.setEpc(tagInfo.getEpc());
                Observable.just(bean)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(bookBean -> addItem(bookBean));

//                if (tagInfo.getScanModel() == AnalyzeImpl.TO_SHELF) {
////                    getShelfByCode(tagInfo.getTag());
//                } else
//                    getBookByCode(tagInfo.getTag());
                break;
        }
    }

    public int getPosition(OfflineCollectItmeViewModel item) {
        return bookItemList.indexOf(item);
    }

    /**
     * 按Tid查询书本
     *
     * @param tid 标签
     */
    private void getBookByTid(String tid) {
        model.getBookByTid(tid)
                .compose(RxUtils.applySchedulersToast(getLifecycleProvider(), this))
                .subscribe(bookBean -> {
                    addItem(bookBean);
                });
    }

    /**
     * 按Tid查询书本
     *
     * @param code 标签
     */
    private void getBookByCode(String code) {
        model.getBookByCode(code)
                .compose(RxUtils.applySchedulersToast(getLifecycleProvider(), this))
                .subscribe(bookBean -> addItem(bookBean));
    }

    /**
     * 添加项目
     *
     * @param bean 豆
     */
    private void addItem(BookBean bean) {
//        Optional<BookBean> any = bookBeans.stream().filter(bookBean -> bookBean.getTid().equals(bean.getTid()))
//                .findAny();
//        if (!any.isPresent()) {sdfasdlkfjasdlk;fjals;kefjqopweiurj
//        for (int i = 0; i < 200; i++) {
            bookItemList.add(new OfflineCollectItmeViewModel(this, bean));
//        }
    }

    public void onItemRemove(ItemViewModel bean) {
        int position = bookItemList.indexOf(bean);
        bookItemList.remove(position);
        adapter.notifyDataSetChanged();
        ToastUtils.showShort("删除成功");
    }

    /**
     * 清除所有数据
     */
    public BindingCommand cleanAllData = new BindingCommand(() -> {
        cleanRFIDCacheNotStop();
        bookItemList.clear();
    });
    /**
     * 清除所有数据
     */
    public BindingCommand conformListing = new BindingCommand(() -> {
        getUC().getFinishEvent().call();
    });


    public List<BookBean> getMatchBooks() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return bookItemList.stream()
                    .map(viewModel -> viewModel.bean.getValue())
                    .collect(Collectors.toList());
        }else{
            return StreamSupport.stream(bookItemList)
                    .map(viewModel -> viewModel.bean.getValue())
                    .collect(java8.util.stream.Collectors.toList());
        }
    }

}
